<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','update'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','delete','getInvite'),
				'expression'=>array($this,'isTopUser'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','createagentcompany','createagentperson'),
				// 'expression'=>array($this,'isTopUser'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{ 
	    $user_id=$_POST['user_id'];
	    $user=User::model()->find("user_id="."'$user_id'");
	   
		$model=new User;	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$model2=new PartnerInfo;
		$model3=new PartnerIncome;
		$model4=new PartnerInvoice;
		$level=$_REQUEST['level'];
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->invite_code=$this->createinvitecode();
			$model->iscustomer=$_POST['User']['iscustomer'];
			$model->invite_user_id=$_POST['invite_user_id'];
			$model2->company_name=$_POST['User']['user_name'];
			$model2->type=$_POST['PartnerInfo']['type'];
			$model->save();
		//print_r($model);
 			if($level==9)
 			{		
 			    $model2->save();		
			}
			if($level==2&&$_POST['invite_user_id']==9&&$_POST['User']['iscustomer']==1)
			{ 
			    $model3->user_name=$user->user_name;
			    $model3->customer_name=$_POST['User']['user_name'];
			    $model3->amount=$this->getAmount($user->user_name);
			    $model3->save();
			    if( $model3->save())
			    {
			        $model4->attributes=$this->getSumAmount($_POST['user_id']);
			    }
			}
			if($model->save())	
			   
				if($_REQUEST['level']!=""){
				$this->redirect(array('admin','level'=>$_REQUEST['level']));
			}
			
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
public function actionCreateAgentCompany(){
		$model1=new User;
		$model2=new AgentCompany;
		if(isset($_POST['User'],$_POST['AgentCompany'])){
			$model1->attributes=$_POST['User'];
			$model2->attributes=$_POST['AgentCompany'];
			$hetong=CUploadedFile::getInstance($model2,'filename');
			if($hetong!=""){

			$filename=$hetong->getName();

			$filesize=$hetong->getSize();

			$filetype=$hetong->getType();

			$model2->hetong=$filename;

			$filename1=iconv("utf-8", "gb2312", $filename);

			$uploadfile=dirname(dirname(dirname(__FILE__)))."/assets/upload/".$filename1;
			$hetong->saveAs($uploadfile,true);
			}
			$user_name=$_POST['User']['user_name'];
			$telephone=$_POST['User']['telephone'];
			$email=$_POST['User']['email'];
			$level=$_POST['User']['level'];
			if($model1->save())
			{
				$user=User::model()->find("user_name="."'$user_name'");
				$model2->user_id=$user->user_id;
				$model2->name=$user_name;
				$model2->phone=$telephone;
				$model2->email=$email;
				$model2->agent_number=AgentCompany::model()->getAgentNumber($model2->user_id);
				if($model2->save())
					AgentPerson::model()->createAgentPerson($user->user_id,$telephone,$email,$user_name,$model2->agent_number);
					$this->redirect(array('admin','level'=>$level));
			}
		}
		$this->render('createagentcompany',array('model1'=>$model1,'model2'=>$model2));
	}
	public function actionCreateAgentPerson(){

		$model1=new User;

		$model2=new AgentPerson;
     
		if(isset($_POST['User'],$_POST['AgentPerson'])){

			$model1->attributes=$_POST['User'];

			$model2->attributes=$_POST['AgentPerson'];

			$user_name=$_POST['User']['user_name'];

			$telephone=$_POST['User']['telephone'];

			$email=$_POST['User']['email'];

			$level=$_POST['User']['level'];
			$company_number=$_POST['AgentPerson']['company_number'];

			if($model1->save())

			{

				$user=User::model()->find("user_name="."'$user_name'");

				$model2->user_id=$user->user_id;

				$model2->name=$user_name;

				$model2->telephone=$telephone;

				$model2->email=$email;

				$model2->agent_number=AgentPerson::model()->getAgentPersonNumber($company_number);

				if($model2->save())

					$this->redirect(array('admin','level'=>$level));

			}

		}

		$this->render('createagentperson',array('model1'=>$model1,'model2'=>$model2));

	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		
        $info=PartnerInfo::model()->findbyattributes(array('company_name'=>$model->user_name));
        //var_dump($info);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->iscustomer=$_POST['User']['iscustomer'];
			$info->type=$_POST['PartnerInfo']['type'];
			
			if($model->save())
			{$info->save();
				$user_id=$model->user_id;
				
				$rs=User::model()->find('user_id='.$user_id);
				$this->redirect(array('admin','level'=>$rs->level));
			}
		}		
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];
		$level=yii::app()->user->level();
		$user_id=yii::app()->request->getParam('user_id');
		if($user_id!=""){
			$sql="select user_id from zy_user where user_id=".$user_id;
		}elseif($level==1){
			if(Yii::app()->request->getParam('level')==2){
				$sql="select user_id from zy_user where level=2";
			}else if(Yii::app()->request->getParam('level')==1){
				$sql="select user_id from zy_user where level=1";
			}elseif(yii::app()->request->getParam('level')==4){
				$sql="select user_id from zy_user where level=4";
			}elseif(yii::app()->request->getParam('level')==5){
				$sql="select user_id from zy_user where level=5";
			}elseif(yii::app()->request->getParam('level')==6){
				$sql="select user_id from zy_user where level=6";
			}elseif(yii::app()->request->getParam('level')==7){
				$sql="select user_id from zy_user where level=7";
			}elseif(yii::app()->request->getParam('level')==9){
				$sql="select user_id from zy_user where level=9";
			}elseif (yii::app()->request->getParam('level')==12)
			{
			$sql="select user_id from zy_user where level=12";
			}elseif (yii::app()->request->getParam('level')==11)
			{
			$sql="select user_id from zy_user where level=11";
			}else{
				$sql="select user_id from zy_user where level=1";
			}
		}elseif(yii::app()->user->level()==2){
			$sql="select user_id from zy_user where user_id=".yii::app()->user->id." or parentId=".yii::app()->user->id;
		}elseif($level==4){
			if(yii::app()->request->getParam(level)==4){
				$sql="select user_id from zy_user where user_id=".yii::app()->user->id;
			}elseif(yii::app()->request->getParam(level)==5){
				$sql="select user_id from zy_user where parentId=".yii::app()->user->id;
			}else{
				$sql="select user_id from zy_user where user_id=".yii::app()->user->id;
			}
		}else{
			$sql="select user_id from zy_user where user_id=".yii::app()->user->id;
		}
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql);
		$results = $command->queryAll();
		for($i=0;$i<count($results);$i++){
			$result[$i]=$results[$i]['user_id'];
		}
		$this->render('admin',array(
			'model'=>$model,
			'results'=>$result,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	protected function isTopUser()
	{
		$level = Yii::app()->user->level();

		return ($level==2 || $level==1 || $level == 9);
	}
	protected function isAdmin()

	{

		$level = Yii::app()->user->level();

		return ($level==1);

	}
	
	//生成邀请码
	public function createinvitecode()
	{
	$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
	for($i = 0; $i <6; $i++) {
		$invite_code .= $pattern{mt_rand(0, 61)};
	}
	$sql="select invite_code from zy_user where invite_code ='".$invite_code."'";
	$connection=Yii::app()->db;
	$command = $connection->createCommand($sql);
	$results = $command->queryAll();
	if($results)
	{
		$this->createinvitecode();	
	}else{
	return $invite_code;
	}
	}
	//根据level获取邀请人
	public function ActiongetInvite()
	{
	    $data=User::model()->findAllByAttributes(array('level'=>$_POST['invite_user_id']));
	    $data=CHtml::listData($data,'user_id','user_name');
	    foreach($data as $value=>$name) {
	        echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
	    }
	}
//通过合作商名称获取提成金额	
	public function getAmount($user_name)
	{   
	    $model=new PartnerIncome;
		$info=PartnerInfo::model()->find("company_name='".$user_name."'");
		$sql='select * from partner_setting where partner_type='.$info->type;
		$rs=yii::app()->db->createCommand($sql)->queryAll();		
	    $sql1="select * from partner_income where user_name='".$user_name."'";
	    $rs1=yii::app()->db->createCommand($sql1)->queryAll();
	    $count= count($rs1);
		if ($count>=$rs[0]['min']&&$count<=$rs[0]['max'])
		    return  $model->amount=$rs[0]['push_money'];
		elseif($count>=$rs[1]['min']&&$count<=$rs[1]['max'])
		    return $model->amount=$rs[1]['push_money'];
		elseif($count>=$rs[2]['min']&&$count<=$rs[2]['max'])
		    return  $model->amount=$rs[2]['push_money'];
		    
	}
	//根据合作商id获取总账单
	public function getSumAmount($user_id)
	{
	    $admin_id=yii::app()->user-id;
	    $admin=User::model()->find("user_id="."'$admin_id'");
	    $user=User::model()->find("user_id="."'$user_id'");
	    $model=new PartnerInvoice;
	    $sql="select * from partner_income where user_name='".$user->user_name."'";
	    $rs=yii::app()->db->createCommand($sql)->queryAll();
	    $sql1='select * from partner_invoice where user_id='.$user_id;
	    $rs1=yii::app()->db->createCommand($sql1)->queryAll();
	    $count=count($rs1);
        if($count==0)
        {
	    $model->issued_user=$admin->user_name;
	    $model->user_id=$user_id;
	    //$model->issued_time=date('Y-m-d H:i:s',time());
	    $model->sumamount=$rs[0]['amount'];
	    $model->undisbursed_amount=$rs[0]['amount'];
	    $model->save();
        }
        else 
        {   $model1=PartnerInvoice::model()->find('user_id='.$user_id);
            $sql2="SELECT * from partner_income where user_name='".$user->user_name."' order by partner_income_id desc";
            $result=yii::app()->db->createCommand($sql2)->queryAll();
            $sum=$model1->sumamount;
            $not_amount=$model1->undisbursed_amount;
            {
            $model1->sumamount=$result[0]['amount']+$sum;
            $model1->undisbursed_amount=$result[0]['amount']+$not_amount;
            }
//             $sum=0;
//             for ($i=0;$i<count($rs);$i++)
//             {
//             $sum=$sum+$rs[$i]['amount'];
//             $model1->sumamount=$sum;
            
//             }
            $model1->save();
        }
	    
	}
}
